import os

# 生成标签类别数据
def get_label_categories():
    return [
        {"name": "电视消费水平", "key": "tvFeeLevel", "labels": ["低消费", "中消费", "高消费", "超高消费"]},
        {"name": "宽带消费水平", "key": "broadbandFeeLevel", "labels": ["低消费", "中消费", "高消费"]},
        {"name": "用户是否挽留", "key": "retentionStatus", "labels": ["是", "否"]},
        {"name": "业务品牌", "key": "businessBrand", "labels": ["品牌A", "品牌B", "品牌C", "品牌D"]},
        {"name": "电视入网程度", "key": "tvTenureLevel", "labels": ["新入网", "中期用户", "长期用户"]},
        {"name": "宽带入网程度", "key": "broadbandTenureLevel", "labels": ["新入网", "中期用户", "长期用户"]},
        {"name": "消费类型", "key": "feeType", "labels": ["基础消费", "增值消费", "混合消费"]}
    ]

# 生成Vue组件
def generate_vue_component(output_dir, label_categories):
    vue_dir = os.path.join(output_dir, "src", "views", "media", "user")
    os.makedirs(vue_dir, exist_ok=True)
    
    # 生成查询参数部分
    query_params = "        queryParams: {\n"
    query_params += "        pageNum: 1,\n"
    query_params += "        pageSize: 10,\n"
    query_params += "        terminalNo: undefined,\n"
    query_params += "        phoneNo: undefined,\n"
    query_params += "        smName: undefined,\n"
    query_params += "        userLabel: undefined,"
    
    for category in label_categories:
        query_params += "\n        " + category["key"] + ": undefined,"
    query_params = query_params.rstrip(",") + "\n        }"
    
    # 生成过滤选项
    filter_options = ""
    for category in label_categories:
        filter_options += "        <el-form-item label=\"" + category["name"] + "\">\n"
        filter_options += "          <el-select v-model=\"queryParams." + category["key"] + "\" placeholder=\"请选择" + category["name"] + "\">\n"
        filter_options += "            <el-option label=\"全部\" value=\"\"></el-option>\n"
        for label in category["labels"]:
            filter_options += "            <el-option label=\"" + label + "\" value=\"" + label + "\"></el-option>\n"
        filter_options += "          </el-select>\n"
        filter_options += "        </el-form-item>\n"
    
    content = '''
<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-loading="loading" label-width="100px">
      <el-form-item label="终端编号" prop="terminalNo">
        <el-input
          v-model="queryParams.terminalNo"
          placeholder="请输入终端编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户编号" prop="phoneNo">
        <el-input
          v-model="queryParams.phoneNo"
          placeholder="请输入用户编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌名称" prop="smName">
        <el-input
          v-model="queryParams.smName"
          placeholder="请输入品牌名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户标签" prop="userLabel">
        <el-select v-model="queryParams.userLabel" placeholder="请选择用户标签">
          <el-option label="全部" value=""></el-option>
          <el-option label="新用户" value="新用户"></el-option>
          <el-option label="潜在流失用户" value="潜在流失用户"></el-option>
          <el-option label="一般用户" value="一般用户"></el-option>
          <el-option label="忠诚用户" value="忠诚用户"></el-option>
          <el-option label="高价值用户" value="高价值用户"></el-option>
        </el-select>
      </el-form-item>
'''
    
    content += filter_options
    
    content += '''      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="终端编号" prop="terminalNo" align="center" />
      <el-table-column label="用户编号" prop="phoneNo" align="center" />
      <el-table-column label="品牌名称" prop="smName" align="center" />
      <el-table-column label="状态名称" prop="runName" align="center" />
      <el-table-column label="用户等级" prop="ownerName" align="center" />
      <el-table-column label="用户标签" prop="userLabel" align="center" />
'''
    
    # 添加7个标签列
    for category in label_categories:
        content += "      <el-table-column label=\"" + category["name"] + "\" prop=\"" + category["key"] + "\" align=\"center\" />\n"
    
    content += '''      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['media:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['media:user:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :page-size.sync="queryParams.pageSize"
      :current-page="queryParams.pageNum"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/media/user"

export default {
  name: "MediaUserList",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户列表
      userList: [],
      // 查询参数
'''
    
    content += query_params
    
    content += '''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
}
</script>
'''
    
    file_path = os.path.join(vue_dir, "index.vue")
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(content)
    
    print("已生成Vue组件: " + file_path)

# 生成后端Controller
def generate_controller(output_dir):
    controller_dir = os.path.join(output_dir, "src", "main", "java", "com", "ruoyi", "web", "controller", "media")
    os.makedirs(controller_dir, exist_ok=True)
    
    content = '''
package com.ruoyi.web.controller.media;

import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.media.domain.MediaUser;
import com.ruoyi.media.service.IMediaUserService;

/**
 * 广电用户Controller
 * 
 * @author ruoyi
 * @date 2025-12-04
 */
@RestController
@RequestMapping("/media/user")
public class MediaUserController extends BaseController
{
    @Autowired
    private IMediaUserService mediaUserService;

    /**
     * 查询广电用户列表
     */
    @PreAuthorize("@ss.hasPermi('media:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(MediaUser mediaUser)
    {
        startPage();
        List<MediaUser> list = mediaUserService.selectMediaUserList(mediaUser);
        return getDataTable(list);
    }

    /**
     * 获取广电用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('media:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(mediaUserService.selectMediaUserById(id));
    }

    /**
     * 新增广电用户
     */
    @PreAuthorize("@ss.hasPermi('media:user:add')")
    @Log(title = "广电用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MediaUser mediaUser)
    {
        return toAjax(mediaUserService.insertMediaUser(mediaUser));
    }

    /**
     * 修改广电用户
     */
    @PreAuthorize("@ss.hasPermi('media:user:edit')")
    @Log(title = "广电用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MediaUser mediaUser)
    {
        return toAjax(mediaUserService.updateMediaUser(mediaUser));
    }

    /**
     * 删除广电用户
     */
    @PreAuthorize("@ss.hasPermi('media:user:remove')")
    @Log(title = "广电用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mediaUserService.deleteMediaUserByIds(ids));
    }
}
'''
    
    file_path = os.path.join(controller_dir, "MediaUserController.java")
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(content)
    
    print("已生成后端Controller: " + file_path)

# 生成Service接口
def generate_service(output_dir):
    service_dir = os.path.join(output_dir, "src", "main", "java", "com", "ruoyi", "media", "service")
    os.makedirs(service_dir, exist_ok=True)
    
    content = '''
package com.ruoyi.media.service;

import java.util.List;
import com.ruoyi.media.domain.MediaUser;

/**
 * 广电用户Service接口
 * 
 * @author ruoyi
 * @date 2025-12-04
 */
public interface IMediaUserService
{
    /**
     * 查询广电用户列表
     * 
     * @param mediaUser 广电用户
     * @return 广电用户集合
     */
    public List<MediaUser> selectMediaUserList(MediaUser mediaUser);

    /**
     * 查询广电用户
     * 
     * @param id 广电用户主键
     * @return 广电用户
     */
    public MediaUser selectMediaUserById(Long id);

    /**
     * 新增广电用户
     * 
     * @param mediaUser 广电用户
     * @return 结果
     */
    public int insertMediaUser(MediaUser mediaUser);

    /**
     * 修改广电用户
     * 
     * @param mediaUser 广电用户
     * @return 结果
     */
    public int updateMediaUser(MediaUser mediaUser);

    /**
     * 批量删除广电用户
     * 
     * @param ids 需要删除的广电用户主键集合
     * @return 结果
     */
    public int deleteMediaUserByIds(Long[] ids);

    /**
     * 删除广电用户信息
     * 
     * @param id 广电用户主键
     * @return 结果
     */
    public int deleteMediaUserById(Long id);
}
'''
    
    file_path = os.path.join(service_dir, "IMediaUserService.java")
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(content)
    
    # 生成Service实现
    impl_content = '''
package com.ruoyi.media.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.media.mapper.MediaUserMapper;
import com.ruoyi.media.domain.MediaUser;
import com.ruoyi.media.service.IMediaUserService;

/**
 * 广电用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-12-04
 */
@Service
public class MediaUserServiceImpl implements IMediaUserService
{
    @Autowired
    private MediaUserMapper mediaUserMapper;

    /**
     * 查询广电用户列表
     * 
     * @param mediaUser 广电用户
     * @return 广电用户
     */
    @Override
    public List<MediaUser> selectMediaUserList(MediaUser mediaUser)
    {
        return mediaUserMapper.selectMediaUserList(mediaUser);
    }

    /**
     * 查询广电用户
     * 
     * @param id 广电用户主键
     * @return 广电用户
     */
    @Override
    public MediaUser selectMediaUserById(Long id)
    {
        return mediaUserMapper.selectMediaUserById(id);
    }

    /**
     * 新增广电用户
     * 
     * @param mediaUser 广电用户
     * @return 结果
     */
    @Override
    public int insertMediaUser(MediaUser mediaUser)
    {
        return mediaUserMapper.insertMediaUser(mediaUser);
    }

    /**
     * 修改广电用户
     * 
     * @param mediaUser 广电用户
     * @return 结果
     */
    @Override
    public int updateMediaUser(MediaUser mediaUser)
    {
        return mediaUserMapper.updateMediaUser(mediaUser);
    }

    /**
     * 批量删除广电用户
     * 
     * @param ids 需要删除的广电用户主键集合
     * @return 结果
     */
    @Override
    public int deleteMediaUserByIds(Long[] ids)
    {
        return mediaUserMapper.deleteMediaUserByIds(ids);
    }

    /**
     * 删除广电用户信息
     * 
     * @param id 广电用户主键
     * @return 结果
     */
    @Override
    public int deleteMediaUserById(Long id)
    {
        return mediaUserMapper.deleteMediaUserById(id);
    }
}
'''
    
    impl_file = os.path.join(service_dir, "impl", "MediaUserServiceImpl.java")
    os.makedirs(os.path.dirname(impl_file), exist_ok=True)
    with open(impl_file, "w", encoding="utf-8") as f:
        f.write(impl_content)
    
    print("已生成后端Service: " + file_path)
    print("已生成后端Service实现: " + impl_file)

# 生成实体类
def generate_entity(output_dir):
    entity_dir = os.path.join(output_dir, "src", "main", "java", "com", "ruoyi", "media", "domain")
    os.makedirs(entity_dir, exist_ok=True)
    
    content = '''
package com.ruoyi.media.domain;

import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * 广电用户对象 media_user_wide_table
 * 
 * @author ruoyi
 * @date 2025-12-04
 */
public class MediaUser
{
    private static final long serialVersionUID = 1L;

    /** 主键ID */
    private Long id;

    /** 终端编号 */
    private String terminalNo;

    /** 用户编号 */
    private String phoneNo;

    /** 品牌名称 */
    private String smName;

    /** 状态名称 */
    private String runName;

    /** 品牌编号 */
    private String smCode;

    /** 用户等级名称 */
    private String ownerName;

    /** 用户等级编号 */
    private String ownerCode;

    /** 状态变更时间 */
    private String runTime;

    /** 完整地址 */
    private String addressoj;

    /** 街道或小区地址 */
    private String estateName;

    /** 开户时间 */
    private String openTime;

    /** 宽带是否生效 */
    private String force;

    /** 用户标签 */
    private String userLabel;

    /** 标签类型 */
    private String labelType;

    /** 新用户标签 */
    private Integer labelNewUser;

    /** 潜在流失用户标签 */
    private Integer labelPotentialChurn;

    /** 一般用户标签 */
    private Integer labelRegularUser;

    /** 忠诚用户标签 */
    private Integer labelLoyalUser;

    /** 高价值用户标签 */
    private Integer labelHighValue;

    /** 创建时间 */
    private Date createTime;

    /** 更新时间 */
    private Date updateTime;

    // 7个标签过滤字段
    private String tvFeeLevel;
    private String broadbandFeeLevel;
    private String retentionStatus;
    private String businessBrand;
    private String tvTenureLevel;
    private String broadbandTenureLevel;
    private String feeType;

    public void setId(Long id)
    {
        this.id = id;
    }

    public Long getId()
    {
        return id;
    }

    public String getTerminalNo() {
        return terminalNo;
    }

    public void setTerminalNo(String terminalNo) {
        this.terminalNo = terminalNo;
    }

    public String getPhoneNo() {
        return phoneNo;
    }

    public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }

    public String getSmName() {
        return smName;
    }

    public void setSmName(String smName) {
        this.smName = smName;
    }

    public String getUserLabel() {
        return userLabel;
    }

    public void setUserLabel(String userLabel) {
        this.userLabel = userLabel;
    }

    public String getTvFeeLevel() {
        return tvFeeLevel;
    }

    public void setTvFeeLevel(String tvFeeLevel) {
        this.tvFeeLevel = tvFeeLevel;
    }

    public String getBroadbandFeeLevel() {
        return broadbandFeeLevel;
    }

    public void setBroadbandFeeLevel(String broadbandFeeLevel) {
        this.broadbandFeeLevel = broadbandFeeLevel;
    }

    public String getRetentionStatus() {
        return retentionStatus;
    }

    public void setRetentionStatus(String retentionStatus) {
        this.retentionStatus = retentionStatus;
    }

    public String getBusinessBrand() {
        return businessBrand;
    }

    public void setBusinessBrand(String businessBrand) {
        this.businessBrand = businessBrand;
    }

    public String getTvTenureLevel() {
        return tvTenureLevel;
    }

    public void setTvTenureLevel(String tvTenureLevel) {
        this.tvTenureLevel = tvTenureLevel;
    }

    public String getBroadbandTenureLevel() {
        return broadbandTenureLevel;
    }

    public void setBroadbandTenureLevel(String broadbandTenureLevel) {
        this.broadbandTenureLevel = broadbandTenureLevel;
    }

    public String getFeeType() {
        return feeType;
    }

    public void setFeeType(String feeType) {
        this.feeType = feeType;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
            .append("id", getId())
            .append("terminalNo", getTerminalNo())
            .append("phoneNo", getPhoneNo())
            .toString();
    }
}
'''
    
    file_path = os.path.join(entity_dir, "MediaUser.java")
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(content)
    
    print("已生成实体类: " + file_path)

# 生成菜单SQL
def generate_menu_sql(output_dir):
    sql_dir = os.path.join(output_dir, "sql")
    os.makedirs(sql_dir, exist_ok=True)
    
    content = '''
-- 广电用户管理菜单
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20000, '广电用户管理', 10000, 1, 'media', 'media/index', 1, 0, 'C', '0', '0', '', 'el-icon-video-camera-solid', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '广电用户管理模块');

-- 广电用户列表菜单
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20001, '用户列表', 20000, 1, 'user', 'media/user/index', 1, 0, 'C', '0', '0', 'media:user:list', '', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '广电用户列表');

-- 新增按钮权限
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20002, '新增用户', 20001, 2, '#', '', 0, 0, 'F', '0', '0', 'media:user:add', '', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '');

-- 修改按钮权限
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20003, '修改用户', 20001, 3, '#', '', 0, 0, 'F', '0', '0', 'media:user:edit', '', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '');

-- 删除按钮权限
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20004, '删除用户', 20001, 4, '#', '', 0, 0, 'F', '0', '0', 'media:user:remove', '', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '');

-- 导出按钮权限
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20005, '导出用户', 20001, 5, '#', '', 0, 0, 'F', '0', '0', 'media:user:export', '', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '');
'''
    
    file_path = os.path.join(sql_dir, "menu_media_user.sql")
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(content)
    
    print("已生成菜单SQL: " + file_path)

# 主函数
def generate_media_user_code():
    # 输出目录
    output_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 获取标签类别
    label_categories = get_label_categories()
    
    # 生成各模块代码
    generate_vue_component(output_dir, label_categories)
    generate_controller(output_dir)
    generate_service(output_dir)
    generate_entity(output_dir)
    generate_menu_sql(output_dir)
    
    print("\n代码生成完成！所有文件保存在: " + output_dir)

if __name__ == "__main__":
    generate_media_user_code()